/**
 * Created by zyx on 2015/9/26.
 */

window.onload = function () {
    //WeixinJSBridgeReady
   /* var stateObj = { foo: "bar" };
    history.pushState(stateObj, "", 'a.html');
    window.onpopstate = function () {

        history.back();
    };*/


    document.getElementById('getImg').onclick = function () {
        var doc = document;
        var iuput1 = doc.getElementById('getImg1');
        var iuput2 = doc.getElementById('getImg2');
        var iuput3 = doc.getElementById('getImg3');

        if(iuput1.value.length == 0) {
            iuput1.click();
        } else if(iuput2.value.length == 0) {
            iuput2.click();
        } else if(iuput3.value.length == 0) {
            iuput3.click();
        }
    };

    for(var i in document.querySelectorAll('input[type="file"]')) {
        (function (num) {
            var input = document.querySelectorAll('input[type="file"]')[i];
            input.onchange = function (e) {
                var doc = document;
                var files = e.target.files;
                if(files && files[0]) {
                    var file = files[0];
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#img'+ num +'').attr('src', e.target.result);
                        $('#img'+ num +'').unbind('click');
                        doc.getElementById('img'+ num +'').onclick = function () {
                            doc.getElementById('getImg'+ num +'').click();
                            doc.getElementById('getImg').innerHTML = '点击上传第'+ (num + 1) +'张图片';
                        };
                        if(num == 3) {
                            doc.getElementById('getImg').className += ' hide';
                        }
                    };
                    reader.readAsDataURL(file);
                }
            };
        })(parseInt(i) + 1);
    };

    document.getElementsByTagName('form')[0].onsubmit = function () {
        var doc = document;
        var necList = doc.querySelectorAll('.nec');
        var error = false;
        for(var j = 0; j < necList.length; j ++) {
            var nec = necList[j];
            if(nec.value.length == 0) {
                nec.className += ' error';
                nec.placeholder = '此项必填';
                error = true;
            }
        }

        if(error) {
            return false;
        }
    };

};